package com.hn.project.rqinspect.service.impl;

import com.hn.common.enums.CommentTypeEnum;
import com.hn.common.enums.FollowStatusEnum;
import com.hn.common.enums.RiskLevelEnum;
import com.hn.common.exception.BusinessException;
import com.hn.common.utils.sql.SqlUtil;
import com.hn.project.rqinspect.domain.database.*;
import com.hn.project.rqinspect.domain.dto.BranchCheckpointDto;
import com.hn.project.rqinspect.domain.dto.BranchDto;
import com.hn.project.rqinspect.domain.vo.BranchVo;
import com.hn.project.rqinspect.domain.vo.QuesCheckRecordVo;
import com.hn.project.rqinspect.mapper.*;
import com.hn.project.rqinspect.service.BranchService;
import com.hn.utils.AssertUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.List;

@Service
public class BranchServiceImpl implements BranchService {

    @Autowired
    private BranchMapper branchMapper;

    @Autowired
    private BranchPartMapper branchPartMapper;

    @Autowired
    private CheckPartTypeMapper checkPartTypeMapper;

    @Autowired
    private BranchCheckpointMapper branchCheckpointMapper;

    @Autowired
    private TaskRecordMapper taskRecordMapper;

    @Autowired
    private TaskMapper taskMapper;

    @Autowired
    private TaskCheckRecordMapper taskCheckRecordMapper;

    @Override
    public List<BranchDto> listBranchDto(BranchVo branchVo) {
        List<BranchDto> branchDtos = branchMapper.listBranchDto(branchVo);
        if (!branchVo.getSimpleFlag()) {
            for (BranchDto branchDto : branchDtos) {
                Integer branchId = branchDto.getId();
                setRiskLevelAndQuesNum(branchId, branchDto);
            }
        }
        return branchDtos;
    }

    @Override
    public BranchDto getBranchDto(Integer branchId) {
        BranchDto branchDto = branchMapper.getBranchDto(branchId);
        if (branchDto != null) {
            setRiskLevelAndQuesNum(branchId, branchDto);
            Integer riskLevel = branchDto.getRiskLevel();
            if (RiskLevelEnum.SECURITY.level.equals(riskLevel)) {
                branchDto.setRemark("真棒,目前无待整改的问题。感谢您对公司" +
                        "安全的守护,安全无小事,请继续保持哦。");
            } else {
                // 查询待整改问题
                List<Integer> branchIds = new ArrayList<>();
                branchIds.add(branchId);
                QuesCheckRecordVo quesCheckRecordVo = new QuesCheckRecordVo();
                quesCheckRecordVo.setBranchIds(branchIds);
                quesCheckRecordVo.setFollowStatus(FollowStatusEnum.CHANGE.status);
                Integer quesNum = taskCheckRecordMapper.countQuesCheckRecord(quesCheckRecordVo);
                branchDto.setTodoQuesNum(quesNum);
            }
        }
        return branchDto;
    }

    private void setRiskLevelAndQuesNum(Integer branchId, BranchDto branchDto) {
        Integer highNum = taskCheckRecordMapper.countByRiskLevel(branchId, RiskLevelEnum.HIGH.level);
        branchDto.setHighRiskLevelNum(highNum);

        Integer secondNum = taskCheckRecordMapper.countByRiskLevel(branchId, RiskLevelEnum.SECOND.level);
        branchDto.setSecondRiskLevelNum(secondNum);

        Integer lowNum = taskCheckRecordMapper.countByRiskLevel(branchId, RiskLevelEnum.LOW.level);
        branchDto.setLowRiskLevelNum(lowNum);

        if (highNum > 0) {
            branchDto.setRiskLevel(RiskLevelEnum.HIGH.level);
            return;
        }
        if (secondNum > 0) {
            branchDto.setRiskLevel(RiskLevelEnum.SECOND.level);
            return;
        }
        if (lowNum > 0) {
            branchDto.setRiskLevel(RiskLevelEnum.LOW.level);
            return;
        }

        branchDto.setRiskLevel(RiskLevelEnum.SECURITY.level);
    }

    @Override
    public List<CheckPartType> listPartType(Integer taskRecordId) {
        TaskRecord taskRecord = taskRecordMapper.selectByPrimaryKey(taskRecordId);
        if (taskRecord == null) {
            throw new BusinessException("暂无任务记录");
        }

        // 查询任务绑定的问卷,查询问卷下的检查项
        Integer taskId = taskRecord.getTaskId();
        Task task = taskMapper.selectByPrimaryKey(taskId);
        if (task == null) {
            throw new BusinessException("暂无任务");
        }

        Integer branchId = taskRecord.getBranchId();
        List<CheckPartType> checkPartTypes = checkPartTypeMapper.listPartType(task.getQuesId(), branchId);
        for (CheckPartType checkPartType : checkPartTypes) {
            Integer partTypeId = checkPartType.getId();

            TaskCheckRecord query = new TaskCheckRecord();
            query.setPartTypeId(partTypeId);
            query.setTaskRecordId(taskRecordId);
            List<TaskCheckRecord> taskCheckRecords = taskCheckRecordMapper.selectByExample(SqlUtil.newExample(query));
            if (taskCheckRecords != null && !taskCheckRecords.isEmpty()) {
                checkPartType.setCheckFlag(1);
            } else {
                checkPartType.setCheckFlag(0);
            }
        }
        return checkPartTypes;
    }

    @Override
    public List<BranchPart> listBranchPart(Integer branchId, Integer partTypeId) {
        return branchPartMapper.listBranchPart(branchId, partTypeId);
    }

    @Override
    public List<BranchCheckpoint> listBranchCheckpoint(Integer branchPartId, Integer taskRecordId) {
        // 查询所有的检查点
        Example example = SqlUtil.newExample(BranchCheckpoint.class);
        example.createCriteria().andEqualTo("branchPartId", branchPartId);
        List<BranchCheckpoint> branchCheckpoints = branchCheckpointMapper.selectByExample(example);

        // 查询所有的检查记录
        example = SqlUtil.newExample(TaskCheckRecord.class);
        example.createCriteria()
                .andEqualTo("branchPartId",branchPartId)
                .andEqualTo("taskRecordId", taskRecordId);
        List<TaskCheckRecord> taskCheckRecords = taskCheckRecordMapper.selectByExample(example);
        if (taskCheckRecords == null || taskCheckRecords.isEmpty()) {
            return branchCheckpoints;
        }

        List<Integer> checkIds = new ArrayList<>();
        for (TaskCheckRecord taskCheckRecord : taskCheckRecords) {
            Integer commentType = taskCheckRecord.getCommentType();
            if (CommentTypeEnum.GOOD.type.equals(commentType)
                    || CommentTypeEnum.BAD.type.equals(commentType)) {
                checkIds.add(Integer.valueOf(taskCheckRecord.getBranchCheckpointId()));
            } else {
                String branchCheckpointId = taskCheckRecord.getBranchCheckpointId();
                for (String checkpointIdSr : branchCheckpointId.split(",")) {
                    checkIds.add(Integer.valueOf(checkpointIdSr));
                }
            }
        }

        for (BranchCheckpoint branchCheckpoint : branchCheckpoints) {
            Integer id = branchCheckpoint.getId();
            if(checkIds.contains(id)){
                branchCheckpoint.setCheckFlag(1);
            }
        }

        return branchCheckpoints;
    }

    @Override
    public List<BranchCheckpointDto> listNoCheckBranchCheckpoint(Integer partTypeId, Integer taskRecordId) {
        TaskRecord taskRecord = taskRecordMapper.selectByPrimaryKey(taskRecordId);
        AssertUtils.notNull(taskRecord, "任务记录不存在");

        // 查询所有的检查记录
        Example example = SqlUtil.newExample(TaskCheckRecord.class);
        example.createCriteria()
                .andEqualTo("taskRecordId", taskRecordId)
                .andEqualTo("partTypeId",partTypeId);
        List<TaskCheckRecord> taskCheckRecords = taskCheckRecordMapper.selectByExample(example);
        List<Integer> containIds = new ArrayList<>();
        List<Integer> noContainIds = new ArrayList<>();

        for (TaskCheckRecord taskCheckRecord : taskCheckRecords) {
            Integer commentType = taskCheckRecord.getCommentType();
            if (CommentTypeEnum.GOOD.type.equals(commentType)
                    || CommentTypeEnum.BAD.type.equals(commentType)) {
                noContainIds.add(Integer.valueOf(taskCheckRecord.getBranchCheckpointId()));
            } else {
                String branchCheckpointId = taskCheckRecord.getBranchCheckpointId();
                for (String checkpointIdSr : branchCheckpointId.split(",")) {
                    containIds.add(Integer.valueOf(checkpointIdSr));
                }
            }
        }

        if (containIds.isEmpty()) {
            containIds = null;
        }

        if (noContainIds.isEmpty()) {
            noContainIds = null;
        }

        Integer branchId = taskRecord.getBranchId();
        return branchCheckpointMapper.listNoCheckBranchCheckpoint(partTypeId, branchId, containIds, noContainIds);
    }

    @Override
    public List<Branch> listBranchByPosition(String lng, String lat) {
        return branchMapper.listBranchByPosition(lng, lat);
    }

    @Override
    public Branch getBranchByPosition(String lng, String lat) {
        List<Branch> branches = branchMapper.listBranchByPosition(lng, lat);
        if (branches == null || branches.isEmpty()) {
            return null;
        }
        return branches.get(0);
    }


}
